package com.hengxinguotong.zhihuichengjian.ui;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.FaceCount;
import com.hengxinguotong.zhihuichengjian.bean.FaceCountListRes;
import com.hengxinguotong.zhihuichengjian.bean.PlanMapRes;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.mapview.MapContainer;
import com.hengxinguotong.zhihuichengjian.widget.mapview.Marker;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/3/14
 */

public class PersonTrailActivity extends BaseActivity implements View.OnClickListener, MapContainer.OnMarkerClickListner{
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.mc_map)
    MapContainer mapContainer;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.bottom_rl)
    RelativeLayout bottomRl;
    @BindView(R.id.name_tv)
    HXTextView nameTv;
    @BindView(R.id.index_tv)
    HXTextView indexTv;
    @BindView(R.id.capture_time_tv)
    HXTextView captureTimeTv;
    @BindView(R.id.close_iv)
    ImageView closeIv;
    private static final int MSG_UPDATE_INFO = 0x110;
    private static final int MSG_UPDATE_MAP = 0x120;
    private String planMapPath, personName, personId;
    private List<FaceCount> faceCountList;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private String pTime, dayOfWeek;
    private String constructionId;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_INFO:
                    List<Marker> mMarkers = new ArrayList<>();
//                    for(List<FaceCount> faceCounts:list){
//                        Marker marker = new Marker(Integer.parseInt(faceCounts.get(0).getX()), Integer.parseInt(faceCounts.get(0).getY()),
//                                R.mipmap.camera, faceCounts.size());
//                        markers.add(marker);
//                    }
                    mMarkers = new ArrayList<>();
                    mMarkers.add(new Marker(0.1f, 0.2f, R.mipmap.camera, 2));
                    mMarkers.add(new Marker(0.3f, 0.7f, R.mipmap.camera, 3));
                    mMarkers.add(new Marker(0.3f, 0.3f, R.mipmap.camera, 4));
                    mMarkers.add(new Marker(0.2f, 0.4f, R.mipmap.camera, 2));
                    mMarkers.add(new Marker(0.8f, 0.4f, R.mipmap.camera, 4));
                    mMarkers.add(new Marker(0.5f, 0.6f, R.mipmap.camera, 1));
                    mMarkers.add(new Marker(0.8f, 0.8f, R.mipmap.camera, 2));
                    mapContainer.setMarkers(mMarkers);
                    mapContainer.setOnMarkerClickListner(PersonTrailActivity.this);
                    break;
                case MSG_UPDATE_MAP:
                    Glide.with(PersonTrailActivity.this)
                            .load(planMapPath)
                            .placeholder(R.mipmap.icon_data_empty)
                            .into(mapContainer.getMapView());
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_trail);
        ButterKnife.bind(this);
        personName = getIntent().getStringExtra("personName");
        titleTv.setText(personName);
        personId = getIntent().getStringExtra("personId");
        constructionId = SPUtil.getString(this,"constructionid");
        planMapPath = SPUtil.getString(PersonTrailActivity.this, constructionId);
        if(Utils.isEmpty(planMapPath)){
            getPlanMap(null);
        }else{
            mHandler.sendEmptyMessage(MSG_UPDATE_MAP);
        }
        initDate();
    }

    private void initDate(){
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        monthOfYear = c.get(Calendar.MONTH);
        dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        if(monthOfYear < 9){
            if(dayOfMonth < 10){
                pTime = year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth;
            }else{
                pTime = year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth;
            }
        }else{
            if(dayOfMonth < 10){
                pTime = year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth;
            }else{
                pTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
            }
        }
        dayOfWeek = Utils.getWeekDay(pTime);
        dateTv.setText(pTime + "\t星期" + dayOfWeek);
        listFaceCount("加载中…");
    }

    private void getPlanMap(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  constructionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/construction/foorplan/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    PlanMapRes planMapRes = gson.fromJson(json, PlanMapRes.class);
                    if(planMapRes.getStatus() == 1){
                        planMapPath = planMapRes.getValue();
                        SPUtil.put(PersonTrailActivity.this, constructionId, planMapPath);
                        mHandler.sendEmptyMessage(MSG_UPDATE_MAP);
                    }else{
                        showToast(planMapRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                showToast(json);
            }
        });
    }

    private void listFaceCount(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  constructionId);
            jsonObject.put("personId",  personId);
            jsonObject.put("TimeStr",  pTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/person/listFaceCount/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    FaceCountListRes faceCountListRes = gson.fromJson(json, FaceCountListRes.class);
                    if(faceCountListRes.getStatus() == 1){
                        faceCountList = faceCountListRes.getValue();
                        if(bottomRl.isShown()){
                            bottomRl.setVisibility(View.GONE);
                        }
                        if(faceCountList == null || faceCountList.size() <= 0){
                            showToast("当天无足迹数据");
                        }else{
//                            mHandler.sendEmptyMessage(MSG_UPDATE_INFO);
                            repeatClear();
                        }
                    }else{
                        showToast(faceCountListRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                showToast(json);
            }
        });
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        PersonTrailActivity.this.year = year;
                        PersonTrailActivity.this.monthOfYear = monthOfYear;
                        PersonTrailActivity.this.dayOfMonth = dayOfMonth;
                        if(monthOfYear < 9){
                            if(dayOfMonth < 10){
                                pTime = year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth;
                            }else{
                                pTime = year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth;
                            }
                        }else{
                            if(dayOfMonth < 10){
                                pTime = year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth;
                            }else{
                                pTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                            }
                        }
                        dayOfWeek = Utils.getWeekDay(pTime);
                        dateTv.setText(pTime + "\t星期" + dayOfWeek);
                        listFaceCount("加载中…");
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }

    @OnClick({R.id.iv_back, R.id.date_tv, R.id.close_iv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.date_tv:
                showWheelViewDialog();
                break;
            case R.id.close_iv:
                bottomRl.setVisibility(View.GONE);
                break;
        }
    }

    List<FaceCount> datas;
    List<List<FaceCount>> list;
    private void repeatClear(){
        datas = new ArrayList<>();
        for(FaceCount faceCount:faceCountList){
            faceCount.setPathName((faceCountList.indexOf(faceCount) + 1) + "号足迹");
            if(datas.size() == 0){
                datas.add(faceCount);
            }else{
                for (FaceCount faceCount1:datas){
                    if(faceCount.getEquipmentId().equals(faceCount1.getEquipmentId())){
                        continue;
                    }else{
                        datas.add(faceCount);
                    }
                }
            }
        }
        list = new ArrayList<>();
        for(FaceCount faceCount:datas){
            List<FaceCount> faceCounts = new ArrayList<>();
            for (FaceCount faceCount1:faceCountList){
                if(faceCount.getEquipmentId().equals(faceCount1.getEquipmentId())){
                    faceCounts.add(faceCount1);
                }
            }
            list.add(faceCounts);
        }
        Log.d("", "repeatClear: " + list);
        mHandler.sendEmptyMessage(MSG_UPDATE_INFO);
    }

    @Override
    public void onClick(View view, int position, int childPosition) {
        FaceCount faceCount = list.get(position).get(childPosition);
        nameTv.setText(faceCount.getProjectCompanyName());
        indexTv.setText(faceCount.getPathName());
        captureTimeTv.setText(faceCount.getTimeStr());
        closeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bottomRl.isShown()){
                    bottomRl.setVisibility(View.GONE);
                }else{
                    bottomRl.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}
